package dai.core.base

import org.joml.Matrix4f
import org.lwjgl.glfw.GLFW
import org.lwjgl.system.MemoryUtil
import java.lang.RuntimeException

class Window(var width: Int, var height: Int, var title: String, private val resizeable: Boolean = true) {

    var winHandler: Long = MemoryUtil.NULL
    var bResize = true

    fun init() {
        GLFW.glfwDefaultWindowHints()
        GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_TRUE)
        GLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, if (resizeable) GLFW.GLFW_TRUE else GLFW.GLFW_FALSE)

        // set opengl 4.1
        GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 4)
        GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 1)
        GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_CORE_PROFILE, GLFW.GLFW_TRUE)

        if (Engine.Debug) {
            GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_DEBUG_CONTEXT, GLFW.GLFW_TRUE)
        }
        winHandler = GLFW.glfwCreateWindow(width, height, title, MemoryUtil.NULL, MemoryUtil.NULL)
        if (winHandler == MemoryUtil.NULL) {
            throw RuntimeException("fail to create window!")
        }
        GLFW.glfwMakeContextCurrent(winHandler)
    }

    fun swap() {
        GLFW.glfwSwapBuffers(winHandler)
        GLFW.glfwPollEvents()
    }

    fun isKeyPress(keyCode: Int) = GLFW.glfwGetKey(winHandler, keyCode) == GLFW.GLFW_PRESS
    fun isKeyUp(keyCode: Int,state:Boolean):Boolean{
        return state && GLFW.glfwGetKey(winHandler, keyCode) == GLFW.GLFW_RELEASE
    }
}
